/**
 * 
 */
package info.niwota.webshot;

import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.net.Uri;
import android.provider.MediaStore.Images;

/**
 * @author qiangli
 * 
 */
public final class ImageUtils {
	private static final Uri STORAGE_URI = Images.Media.EXTERNAL_CONTENT_URI;

	/**
	 * 
	 */
	private ImageUtils() {
	}

	/**
	 * This is copied from ImageManager and may break
	 * @param path
	 * @return
	 */
	public static String getBucketId(String path) {
		return String.valueOf(path.toLowerCase().hashCode());
	}
	
	public static boolean saveImage(File file, Bitmap source) {
		OutputStream os = null;
		try {
			os = new FileOutputStream(file);
			if (source != null) {
				source.compress(CompressFormat.JPEG, 75, os);
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeSilently(os);
		}
		return false;
	}

	private static void closeSilently(Closeable c) {
		if (c == null) {
			return;
		}
		try {
			c.close();
		} catch (Throwable t) {
			// do nothing
		}
	}

	public static Uri addImage(ContentResolver cr, File file, String title) {
		return addImage(cr, file, title, System.currentTimeMillis(), null);
	}

	public static Uri addImage(ContentResolver cr, File file, String title,
			long dateTaken, Location location) {
		//
		ContentValues values = new ContentValues(8);
		values.put(Images.Media.TITLE, title);
		values.put(Images.Media.DISPLAY_NAME, file.getName());
		values.put(Images.Media.DATE_TAKEN, dateTaken);
		values.put(Images.Media.MIME_TYPE, "image/jpeg");
		values.put(Images.Media.ORIENTATION, 0);
		values.put(Images.Media.DATA, file.getPath());
		if (location != null) {
			values.put(Images.Media.LATITUDE, location.getLatitude());
			values.put(Images.Media.LONGITUDE, location.getLongitude());
		}
		return cr.insert(STORAGE_URI, values);
	}
	
    public static Bitmap getImageBitmap(Uri uri) {
        Bitmap bm = null;
        try {
        	if (uri.getScheme().equals("file")) {
    			String p = uri.getPath();
    			bm = BitmapFactory.decodeFile(p);
        	}
       } catch (Exception e) {
          e.printStackTrace();
       }
       return bm;
    } 
}
